package ming;

import db.Database;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getRequestDispatcher("/login.jsp").forward(request,response);

    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        String name = request.getParameter("name");
        String pw = request.getParameter("password");


        try {
            Database database = new Database();
            User usedata = database.login(name,pw);
            if (usedata == null) {
                request.setAttribute("result", "登录失败，请重新输入");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            } else {

                request.setAttribute("result", "登录成功，欢迎"+name);
                request.getRequestDispatcher("/main.jsp").forward(request,response);
                //把用户名以"name"放进session
                request.getSession().setAttribute("name", name);

            }
        }

        catch (SQLException throwables){
            throwables.printStackTrace();
        }
        catch(ClassNotFoundException e) {
            e.printStackTrace();
        }

        request.getRequestDispatcher("/login.jsp").forward(request,response);
    }
}
